/**
 * @author:稀饭
 * @time:上午8:04:53
 * @filename:AreaDAOImpl.java
 */
package ssh.rice.self.daoimpl;

import java.util.Iterator;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.Transaction;

import ssh.rice.self.dao.AreaDao;
import ssh.rice.self.entity.Area;
import ssh.rice.self.entity.User;
import ssh.rice.self.util.HibernateUtils;

public class AreaDAOImpl implements AreaDao {
	private HibernateUtils hibernateUtils;

	public void setHibernateUtils(HibernateUtils hibernateUtils) {
		this.hibernateUtils = hibernateUtils;
	}

	/**
	 * @Title: add
	 * @Description: 添加
	 * @param area
	 * @return id或者-1
	 */
	@Override
	public int add(Area area, int uid) {
		// TODO Auto-generated method stub
		int index = -1;
		Session session = hibernateUtils.getSession();
		Transaction tx = session.beginTransaction();
		try {
			User user = (User) session.get(User.class, uid);
			Set<Area> set = user.getAreas();
			Iterator<Area> iterator = set.iterator();
			while (iterator.hasNext()) {
				Area a = iterator.next();
				System.out.println(a.getPlace());
				if (a.getPlace().equals(area.getPlace())) {
					area = null;
				}
			}
			if (area != null) {
				area.setUser(user);
				session.save(area);
				index = area.getAid();
				tx.commit();
			}
		} catch (Exception e) {
			tx.rollback();
		} finally {
			hibernateUtils.closeSession(session);
		}
		return index;
	}
}
